<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {ElMessage} from "element-plus";
import {savePurchase} from '@/api/purchase/purchase'
import ChooseGoods from "@/views/set/goods/ChooseGoods.vue";
import ChooseSupplier from "@/views/set/supplier/ChooseSupplier.vue";
import host from '@/utils/env.js'
import {options} from "axios";
import {getWarehouseList} from '@/api/warehouse/list'
import {getUser} from "@/utils/session";
//表格数据
const tableData = ref([])

//初始化10行
function init() {
  for (let i = 1; i <= 4; i++) {
    addRow()
  }
}

function addRow() {
  tableData.value.push({
    goodsId: "",
    goodsname: "",
    unit: "",
    warehouse: "",
    num: 0,
    price: 0,
    rate: 0,
    rateMoney: 0,
    money: 0,
    note: "",
    wid: 0,
    tmpPur:{},
    show: {}
  })
}

//单元格双击事件
const lastRow = ref({})//记录上一次双击的是哪一行
function cellck(row, column) {
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
  let tmp = column.property;
  row.show[tmp] = true;
  //记录双击的行
  lastRow.value = row;
}

//删除行
const purchaseRef = ref(null)//表格引用
function delRow() {
  let rows = purchaseRef.value.getSelectionRows()
  if (rows.length == 0) {
    ElMessage({
      message: "请选择要删除的行！",
      type: "warning"
    });
  }
  rows.forEach(r => {
    removeData(r)
  })
}

//从tableData移除行，r代表要移除的行
function removeData(r) {
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //获取当前行对象
    let tmp = tableData.value[i];
    //判断tmp是否是要删除的对象r
    if (tmp == r) {
      tableData.value.splice(i, 1);
      break;//中止循环
    }
  }
}

//采购单
const purchaseForm = ref({
  supplierId: 0,
  supplierName: "",
  billDate: "",
  note: "",
  rate: 0,
  rateMoney: 0,
  money: 0,
  pay: 0,
  accountId: 0,
  debt: 0,
  prepared: "",
  contracts: []
})

//新增保存
async function save() {
  let detail = [];//保存用户填写的明细
  //便利表格数据
  tableData.value.forEach(r => {
    //判断当前对象中是否选择了商品 如果是，加入到明细
    if (r.goodsname != undefined && r.goodsname != "") {
      r.wid=r.tmpPur.id
      r.warehouse=r.tmpPur.name
      detail.push(r)
    }
  })
  if (detail.length == 0) {
    ElMessage({
      message: "采购明细不能为空!",
      type: "warning"
    })
    return
  }
  //参数值
  let data = purchaseForm.value;//采购单基本信息
  //将明细加入采购单
  data.purchaseDetailList = detail;
  //保存
  let res = await savePurchase(data);
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    })
  }
}

//侦听器
watch(tableData, (n) => {
  //遍历表格明细  计算折扣额  采购金额
  tableData.value.forEach(row => {

    if (row.num > 0 && row.price > 0) {
      //未优惠前总金额
      let total = row.num * row.price;
      //计算折扣额
      let tmpRateMoney = 0;
      if (row.rate > 0) {
        tmpRateMoney = total * (row.rate / 100);
        //更新当前行的折扣金额
        row.rateMoney = tmpRateMoney;
      }
      //计算采购金额 总金额 减去折扣金额
      row.money = total - tmpRateMoney;
    }
  });
}, {
  deep: true
});
//商品选择
const isshowchoose = ref(false);//是否显示商品选择框
//选择商品
function choose(rows) {
  if (rows.length == 0) {
    return
  }
  //获取选择行的索引
  let index = -1;
  //遍历表格数据，查询选择的第一个对象的未知
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //临时对象
    let tmp = tableData.value[i];
    if (tmp == lastRow.value) {
      index = i;
      break;
    }
  }
  if (index == -1)
    return;
  //遍历选择的商品
  for (let i = 0, len = rows.length; i < len; i++) {
    //临时对象
    let obj = tableData.value[index];
    obj.goodsId = rows[i].id;
    obj.goodsname = rows[i].name;
    obj.price = rows[i].price;
    obj.unit = rows[i].unit;
    index++;
  }
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
}

//供应商选择
const isshowsupplier = ref(false);//是否显示选择供应商
//选择供应商
function chg(row) {
  console.log(row)
  purchaseForm.value.supplierId = row.id;
  purchaseForm.value.supplierName = row.name;
}

//合同上传
const fileList = ref([])

function handleChange(res, uploadFile) {
  //获取接口返回数据
  if (res.code == 200) {
    //上传成功获取上传后的路径和附件名称
    let tmp = {};
    tmp.path = res.data;
    tmp.filename = uploadFile.name;
    purchaseForm.value.contracts.push(tmp);
  }
}

//文件列表移除
function rm(updateFile) {
  //将指定的文件从purchaseForm中移除
  //获取要删除的合同路径
  let path = updateFile.response.data;
  let index = -1;
  //查询
  for (let i = 0, len = purchaseForm.value.contracts.length; i < len; i++) {
    //临时对象
    let tmp = purchaseForm.value.contracts[i];
    if (tmp.path == path) {
      index = i;
      break;
    }
  }
  if (index != -1) {
    //从purchaseForm中移除
    purchaseForm.value.contracts.splice(index, 1);
  }
}

const options = ref()
async function getById(id){
  if (id==''){
    ElMessage({
      message: '请选择商品',
      type: 'warning',
    })
    return
  }
  let data = {
    "goodsId":id,
    "eid":getUser().eid
  }
  let res = await getWarehouseList(data)
  if (res.code == 200){
    options.value = res.data
  }
}
function shib() {
  ElMessage({
    message: '上传失败，文件大小异常！',
    type: 'warning',
  })
}

//-----------生命周期-----------
onMounted(() => {
  init()
})
</script>

<template>
  <div class="root">
    <!--工具条-->
    <div class="toolbar">
      <el-button type="primary" size="small">保存并新增</el-button>
      <el-button type="primary" size="small" @click="save">保存</el-button>
    </div>
    <!--第一行 -->
    <el-row style="margin-top: 20px">
      <el-col :span="8">
        供应商:<input type="text" @click="isshowsupplier = true" placeholder="请选择供应商" class="ipt"
                      v-model="purchaseForm.supplierName"/>
      </el-col>
      <el-col :span="8">
        单据日期:
        <el-date-picker type="date" placeholder="请选择" value-format="YYYY-MM-DD" size="small"
                        v-model="purchaseForm.billDate"/>
      </el-col>
      <el-col :span="8"> 单据编号：CG23523421</el-col>
    </el-row>

    <div class="detail">
      <!--明细-->
      <div class="detail-title">
        <span>采购明细</span>
        <el-button type="primary" size="small" @click="addRow">增行</el-button>
        <el-button type="primary" size="small" @click="delRow">删行</el-button>
      </div>
      <!--列表-->
      <el-table :data="tableData" style="width: 100%" stripe border @cell-click="cellck" ref="purchaseRef">
        <el-table-column type="selection" width="50" header-algin="center" align="center"/>
        <el-table-column type="index" label="序号" width="80" header-algin="center" align="center"/>

        <el-table-column prop="goodsname" label="商品" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{ row.goodsname }}</span>
            <el-input v-else v-model="row.goodsname" placeholder="点击选择商品" @click="isshowchoose = true"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" width="80" header-algin="center" align="center"/>
        <!--    仓库    -->
        <el-table-column prop="tmpPur.name" label="仓库" width="120" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.tmpPur.name
              }}</span>
            <el-select
              v-else
              v-model="row.tmpPur"
              placeholder="Select"
              style="width: 240px"
              @click="getById(row.goodsId)"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="num" label="数量" width="150" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.num
              }}</span>
            <el-input-number v-else v-model="row.num" size="small" :min="0"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="单价" width="100" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.price
              }}</span>
            <el-input-number v-else v-model="row.price" size="small" :min="0" :precision="2"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="rate" label="折扣率" width="150" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.rate
              }}</span>
            <el-input-number v-else v-model="row.rate" size="small" :min="0" :max="100"
                             :precision="2"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="rateMoney" label="折扣额" width="100" header-algin="center" align="center"/>
        <el-table-column prop="money" label="采购金额" width="100" header-algin="center" align="center"/>
        <el-table-column prop="note" label="备注" width="180" header-algin="center" align="center"/>
      </el-table>
      <!--   备注信息   -->
      <div>
        <input type="text" placeholder="填写订单备注信息" class="note" v-model="purchaseForm.note"/>
      </div>
    </div>
    <!--  优惠  -->
    <el-row style="margin-top:20px">
      <el-col :span="6">优惠率:<input type="text" class="ipt" v-model="purchaseForm.rate"/></el-col>
      <el-col :span="6">优惠金额:<input type="text" class="ipt" v-model="purchaseForm.rateMoney"/></el-col>
      <el-col :span="6">优惠后金额:<input type="text" class="ipt" v-model="purchaseForm.money"/></el-col>
      <el-col :span="6">本次付款:<input type="text" class="ipt" v-model="purchaseForm.pay"/></el-col>
    </el-row>
    <!--  账户合同  -->
    <el-row style="margin-top:20px">
      <el-col :span="6">结算账号:<input type="text" class="ipt" v-model="purchaseForm.accountId"/></el-col>
      <el-col :span="6">本次欠款:<input type="text" class="ipt" v-model="purchaseForm.debt"/></el-col>
      <el-col :span="6">采购合同:<input type="text" class="ipt"/></el-col>
      <el-upload v-model:file-list="fileList" class="upload-demo" :action="host + '/upload'" :on-success="handleChange"
                 :on-remove="rm" :on-error="shib" style="width: 120px">
        <el-button type="primary" size="small" style="margin-right: 10px">上传</el-button>
        <template #tip>
          <div class="el-upload__tip" style="margin-left: 5px; width: 30px">
            jpg/png
          </div>
        </template>
      </el-upload>
      <el-button type="primary" size="small">查看</el-button>
    </el-row>
    <!--  制单人  -->
    <el-row style="margin-top: 20px">
      <el-col :span="6">制单人:<input type="text" class="ipt" v-model="purchaseForm.prepared"/></el-col>
      <el-col :span="18">&nbsp;</el-col>
    </el-row>
    <!--  选择商品  -->
    <ChooseGoods :visible="isshowchoose" @choose="choose" @close="isshowchoose = false"></ChooseGoods>
    <!--  选择供应商  -->
    <ChooseSupplier :visible="isshowsupplier" @close="isshowsupplier = false" @choose="chg"></ChooseSupplier>
  </div>
</template>

<style scoped>
.root {
  border: #ebeef5 solid 1px;
  background-color: #fff;
  height: 100%;
  padding-left: 20px;
}

.toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
}

.ipt {
  width: 200px;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  padding-left: 10px;
}

.detail {
  margin-right: 20px;
  margin-top: 30px;
  padding-left: 10px;
}

.detail-title {
  height: 40px;
  line-height: 40px;
  border: #ebeef5 solid 1px;
  border-bottom-style: none;
  padding-left: 10px;
}

.detail-title button {
  margin-left: 10px;
}

.note {
  width: 100%;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  margin-top: 20px;
}
</style>
